<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addNewRole">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区- -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列：展示角色权限 -->
        <el-table-column type="expand" label="~">
          <template slot-scope="scope">
            <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id"
              :class="['bdbottom',i1==0?'bdtop':'','vcenter']">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 三级权限 -->
              <el-col :span="19">
                <!-- 通过for渲染二级权限 -->
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="['vcenter',i2==0?'':'bdtop']">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 第三级权限 -->
                  <el-col :span="18">
                    <el-tag v-for="(item3,i3) in item2.children" :key="item3.id" type="warning" closable
                      @close="removeRightById(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="roleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="roleDelete(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightBialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限 -->
    <el-dialog
    title="提示"
    :visible.sync="setRightDialogVisible"
    width="50%">
    <!-- 树形控件 -->
    <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defaultKeys" ref="treeRef"></el-tree>
    <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
    </span>
    </el-dialog>
    <!-- 添加新角色 -->
    <el-dialog
    title="提示"
    :visible.sync="addRoleDialogVisible"
    width="50%" @closed="roleDialogClosed">
    <span slot="footer" class="dialog-footer">
        <el-form :model="addRoleRuleForm" :rules="addRoleRules" ref="addRoleRuleFormRef" label-width="70px">
            <el-form-item label="用户名" prop="roleName">
                <el-input v-model="addRoleRuleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="roleDesc">
                <el-input v-model="addRoleRuleForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewRoleDialogVisible">确 定</el-button>
    </span>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog
    title="提示"
    :visible.sync="editRoleDialogVisible"
    width="50%" @closed="roleDialogClosed">
    <span slot="footer" class="dialog-footer">
        <el-form :model="editRoleRuleForm" :rules="addRoleRules" ref="editRoleRuleFormRef" label-width="70px">
            <el-form-item label="用户名" prop="roleName">
                <el-input v-model="editRoleRuleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="roleDesc">
                <el-input v-model="editRoleRuleForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleDialog">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        // 获取所有角色列表
        roleList: [],
        // 控制分配对话框的显示与隐藏
        setRightDialogVisible:false,
        // 获取到的所有权限数据（树形控件）
        rightsList:[],
        // 树形控件的绑定对象
        treeProps:{
            label:'authName',
            children:'children'
        },
        // 默认选中的节点id数组
        defaultKeys:[],
        // 保存当前即将分配权限的id
        roleId:'',
        // 添加新用户对话框显示与隐藏
        addRoleDialogVisible:false,
        // 添加新用户信息
            /*深坑：v-model要与prop变量保持一致，否则无用*/
        addRoleRuleForm:{
            roleName:'',
            roleDesc:''
        },
        // 添加新用户信息时验证
        addRoleRules:{
            roleName:[
                { required: true, message: '请输入用户名', trigger: 'blur' },
                { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
            ],
            roleDesc:[
                { required: false, message: '请输入用户描述', trigger: 'blur' },
                { min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }
            ]
        },
        // 编辑用户对话框显示与隐藏
        editRoleDialogVisible:false,
        // 编辑用户信息
        editRoleRuleForm:{
            roleName:'',
            roleDesc:''
        },
        // 验证信息跟添加的一样，可用，但编辑信息别用
      }
    },
    created() {
      this.getRolesList()
    },
    methods: {
      // 获取所有角色的列表
      async getRolesList() {
        let {
          data: res
        } = await this.$http.get('roles')
        if (res.meta.status != 200) return this.$message.error(res.meta.msg)
        this.roleList = res.data
      },
      // 根据id删除角色权限
      async removeRightById(role, id) {
        let confirmRes = await this.$confirm('是否删除该权限?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .catch(err => err)
        if (confirmRes == 'confirm') {
          let {
            data: res
          } = await this.$http.delete(`roles/${role.id}/rights/${id}`)
          if (res.meta.status != 200) return this.$message.error(res.meta.msg)
          // this.getRolesList() 不推荐使用，会造成页面刷新，权限列表展示变为关闭
          role.children = res.data
          this.$message.success('已删除该权限！')
        } else {
          return this.$message.info('取消删除！')
        }
      },
    //   展示分配权限的对话框
    async showSetRightBialog(role){
        this.roleId=role.id
        // 获取所有权限
        let {data:res}=await this.$http.get('rights/tree')
        if(res.meta.status!=200) return this.$message.error(res.meta.msg)
        this.rightsList=res.data //保存获取到的权限数据
        // 通过递归获取三级节点的id
            //注意：一定要清空存放选中id权限的数组defaultKeys，否则累加造成错误
        this.getLeafKeys(role,this.defaultKeys=[])
        this.setRightDialogVisible=true
    },
    // 通过递归获取三级权限的id
    getLeafKeys(node,arr){
        if(!node.children){ //无children属性则为三级节点
            return arr.push(node.id)
        }
        node.children.forEach(item=>{
            this.getLeafKeys(item,arr)
        })
    },
    // 点击选择框为角色分配权限
    async allotRights(){
        // ES6展开运算符...，合并成一个新数组
        let keys=[...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()]
        let idStr=keys.join(',') //分割成后台需要的传值形式
        let {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
        if(res.meta.status!=200) return this.$message.error(res.meta.mag)
        this.$message.success(res.meta.msg)
        this.getRolesList()
        this.setRightDialogVisible=false
    },
    // 点击添加新用户按钮
    addNewRole(){
        this.addRoleDialogVisible=true
    },
    // 添加新用户
    addNewRoleDialogVisible(){
        // 预校验
        this.$refs.addRoleRuleFormRef.validate(async val=>{
            if(!val) return //校验失败
            let {data:res}=await this.$http.post('roles',{roleName:this.addRoleRuleForm.roleName,roleDesc:this.addRoleRuleForm.roleDesc})
            if(res.meta.status!=201) return this.$message.error(res.meta.msg)
            this.$message.success(res.meta.msg)
            this.getRolesList()
            this.addRoleDialogVisible=false
        })
        
    },
    // 删除用户
    async roleDelete(id){
        // 询问是否删除
        let confirmRes=await this.$confirm('永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // return 捕获报错
        .catch(err=>err)
        /* 若删除，返回字符串 confirm
           若取消，返回字符串 cancel
        */
       if(confirmRes=='confirm'){
         let {data:res}=await this.$http.delete('roles/'+id)
         if(res.meta.status!=200) return this.$message.error(res.meta.msg)
         this.$message.success('已删除！')
         this.getRolesList()
       }
    },
    // 点击编辑用户信息按钮，储存id
    roleEdit(info){
        // 填充编辑框数据
        this.editRoleRuleForm=info
        this.editRoleDialogVisible=true
    },
    // 编辑用户信息
    editRoleDialog(){
         this.$refs.editRoleRuleFormRef.validate(async val=>{
            if(!val) return //校验失败
            let {data:res} = await this.$http.put('roles/'+this.editRoleRuleForm.id,{roleName:this.editRoleRuleForm.roleName,roleDesc:this.editRoleRuleForm.roleDesc})
            if(res.meta.status!=200) return this.$message.error(res.meta.msg)
            this.editRoleDialogVisible=false
            this.getRolesList()
            this.$message.success('修改成功！')
         })
        
    },
    // 监听关闭对话框
    roleDialogClosed(){
        // 清空表单数据
        this.$refs.addRoleRuleFormRef.resetFields()
        this.$refs.editRoleRuleFormRef.resetFields()
    }
    },
  }

</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }

</style>
